package com.luban.springmybatis;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;

public class MyMapperScannerRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * 注册bean定义
     *
     * @param importingClassMetadata importingClassMetadata
     * @param registry               registry
     */
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //获取包扫描的路径
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MyMapperScan.class.getName()));
        String[] basePackages = annotationAttributes.getStringArray("basePackages");
        for (String basePackage : basePackages) {
            //自定义MapperScanner，使用spring的扫描,重写doScan()
            MyMapperScanner scanner = new MyMapperScanner(registry);
            scanner.addIncludeFilter(new TypeFilter() {
                public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                    return true;
                }
            });
            scanner.scan(basePackage);
        }
    }
}
